// AuthService.java（新增 register 方法）
package com.huitongmaoyi.ai.service;

import com.huitongmaoyi.ai.entity.User;
import com.huitongmaoyi.ai.util.DBUtil;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;

public class AuthService {
    private Map<String, User> userCache = new HashMap<>();

    // ===== 登录方法=====
    public boolean login(String username, String password) {
        if (userCache.containsKey(username)) {
            User user = userCache.get(username);
            return user != null && user.matches(username, password);
        }

        String sql = "SELECT * FROM users WHERE username = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, username);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                String dbPassword = rs.getString("password");
                if (dbPassword.equals(password)) {
                    User user = new User(username, password);
                    userCache.put(username, user);
                    return true;
                }
            }
        } catch (SQLException e) {
            System.err.println("数据库查询失败: " + e.getMessage());
        }
        return false;
    }

    // ===== 新增：注册方法 =====
    public boolean register(String username, String password) {
        // 1. 校验输入
        if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty()) {
            System.out.println("❌ 用户名或密码不能为空！");
            return false;
        }

        // 2. 检查用户名是否已存在
        if (userExists(username)) {
            System.out.println("❌ 用户名 '" + username + "' 已存在，请换一个！");
            return false;
        }

        // 3. 插入新用户
        String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, username.trim());
            stmt.setString(2, password.trim());
            int rows = stmt.executeUpdate();

            if (rows > 0) {
                System.out.println("✅ 注册成功！用户名：" + username);
                return true;
            }
        } catch (SQLException e) {
            System.err.println("❌ 注册失败：" + e.getMessage());
        }
        return false;
    }

    // 辅助方法：检查用户名是否存在
    private boolean userExists(String username) {
        String sql = "SELECT 1 FROM users WHERE username = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, username);
            ResultSet rs = stmt.executeQuery();
            return rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}